//
//  YH_CardMangerViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/10/27.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_CardMangerViewController.h"

@interface YH_CardMangerViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,ASIHTTPRequestDelegate>{
    NSString *state;//判断是个人还是企业
    
    UIImageView *compangImage;//企业图
    UIImageView *personImage;//个人图
    
    MBProgressHUD *postHud;
    NSString *filePath;//内容图片地址
    NSString *path;
    
    UIImagePickerController *imgPC;//UIImagePickerController对象
    UIImage *image;//最终的图片
    NSString *filename;
    NSString *imgFileByte;//图片上传filebyte参数
    //参数
    NSString *action;
    NSDictionary *paramsDict;
    
    ASIFormDataRequest *postUploadFile;//发送上传图片请求
    ASIFormDataRequest *postUpload;//发送请求
    ASIFormDataRequest *getCardMain;//获取详情
    
    BOOL add;//添加或者修改
    NSString *path1;//获取企业图path
    NSString *path2;//获取个人图path
}

@end

@implementation YH_CardMangerViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    add = NO;
    //标题
    [self setNavUI];
    [self setUI];
    //获取card详情
    [self getMain];
    compangImage.contentMode = UIViewContentModeScaleAspectFit;
    personImage.contentMode = UIViewContentModeScaleAspectFit;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark Custom Method

-(void)setNavUI{
    self.navigationController.navigationBarHidden = NO;
    self.navigationItem.title = @"证件上传";
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
}
-(void)setUI{
    //ScrollView
    UIScreen *screen = [UIScreen mainScreen];
    UIScrollView *mainView = [[UIScrollView alloc]initWithFrame:screen.bounds];
    mainView.alwaysBounceVertical = YES;
    mainView.contentSize = CGSizeMake(screen.bounds.size.width, 568);
    [self.view addSubview:mainView];
    //企业证件视图
    UIView *companyView = [[UIView alloc]initWithFrame:CGRectMake(10, 10, screen.bounds.size.width - 20 , 200)];
    companyView.backgroundColor = [UIColor whiteColor];
    companyView.layer.cornerRadius = 5.0;
    //企业照片
    compangImage = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, 140, 140)];
    compangImage.image = [UIImage imageNamed:@"placeholder"];
    //初始化单击手势
    UITapGestureRecognizer *tgrSingle = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(compangImageTap:)];
    tgrSingle.numberOfTouchesRequired = 1; //定义需要一个手指
    tgrSingle.numberOfTapsRequired = 1; //定义需要轻拍一次
    compangImage.userInteractionEnabled = YES;
    [compangImage addGestureRecognizer:tgrSingle];
    [companyView addSubview:compangImage];
    //企业说明
    UITextView *describe = [[UITextView alloc]initWithFrame:CGRectMake(170, 20, 120 , 100)];
    describe.font = [UIFont systemFontOfSize:14];
    describe.text = @"企业公司及其他机构请上传营业执照（无营业执照,请上传组织机构代码证）";
    //describe.editable = NO;
    describe.userInteractionEnabled = NO;
    [companyView addSubview:describe];
    //企业button
    UIButton *companyBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    companyBtn.frame = CGRectMake(180, 130, 80, 30);
    [companyBtn setTitle:@"保存" forState:UIControlStateNormal];
    [companyBtn addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
    [companyView addSubview:companyBtn];
    
   
    [mainView addSubview:companyView];
    //个人证件视图
    UIView *personView = [[UIView alloc]initWithFrame:CGRectMake(10, 220, screen.bounds.size.width - 20 , 200)];
    personView.backgroundColor = [UIColor whiteColor];
    personView.layer.cornerRadius = 5.0;
    //个人照片
    personImage = [[UIImageView alloc]initWithFrame:CGRectMake(20, 20, 140, 140)];
    personImage.image = [UIImage imageNamed:@"placeholder"];
    //初始化单击手势
    UITapGestureRecognizer *tgrSingle2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(compangImageTap2:)];
    tgrSingle2.numberOfTouchesRequired = 1; //定义需要一个手指
    tgrSingle2.numberOfTapsRequired = 1; //定义需要轻拍一次
    personImage.userInteractionEnabled = YES;
    [personImage addGestureRecognizer:tgrSingle2];
    [personView addSubview:personImage];
    //个人说明
    UITextView *per_describe = [[UITextView alloc]initWithFrame:CGRectMake(170, 20, 120 , 100)];
    per_describe.font = [UIFont systemFontOfSize:14];
    per_describe.text = @"个人请上传身份证";
   
    per_describe.userInteractionEnabled = NO;
    [personView addSubview:per_describe];
    //个人button
    UIButton *per_companyBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    per_companyBtn.frame = CGRectMake(180, 130, 80, 30);
    [per_companyBtn setTitle:@"保存" forState:UIControlStateNormal];
    [per_companyBtn addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
    [personView addSubview:per_companyBtn];

    [mainView addSubview:personView];
    [self.view addSubview:mainView];
}
//获取card详情
-(void)getMain{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        //BOOL b = postHud.hidden;
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            if (postUpload) {
                postHud.hidden = NO;
                return;
            }
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在请求数据，请稍后...";
        }
        
        getCardMain = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        getCardMain.requestMethod = @"POST";
        // 设置超时时间
        getCardMain.timeOutSeconds = 60;
        getCardMain.delegate = self;
        // 设置参数
        NSString *actionStr = @"IDCardmain";
        paramsDict = @{@"uid":UNAME};
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, actionStr,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        getCardMain.postBody = [paramsData mutableCopy];
        
        [getCardMain startAsynchronous];
    }

}

-(void)back{
    [getCardMain cancel];
    [postUploadFile cancel];
    [postUpload cancel ];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 点击选择图片
-(void)compangImageTap:(id)sender{
    NSLog(@"11");
    state = @"company";
    [self getPhoto];
}

-(void)compangImageTap2:(id)sender{
    NSLog(@"22");
    state = @"person";
    [self getPhoto];
}
#pragma mark 保存
-(void)save:(id)sender{
    NSLog(@"111");
    if (imgFileByte == nil) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请先选择图片" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [self postRequest];
}
#pragma mark 选择图片
-(void)getPhoto{
    UIActionSheet *sheet;
    sheet  = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
    sheet.tag = 255;
    [sheet showInView:self.view];
}
#pragma mark UIActionSheet Delegate Method

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:{
            //NSLog(@"1");
            //取消
        }break;
        case 1:{
            //NSLog(@"2");
            //拍照
            // 检查设备是否可用
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                
                // 创建UIImagePickerController对象
                imgPC = [[UIImagePickerController alloc]init];
                // 设置源类型（确定是调用摄像头还是调用图片库）
                imgPC.sourceType = UIImagePickerControllerSourceTypeCamera;
                // 设置允许编辑
                imgPC.mediaTypes = @[(NSString*)kUTTypeImage];
                imgPC.allowsEditing = YES;
                // 设置代理对象
                imgPC.delegate = self;
                
                // 弹出模式视图控制器
                [self presentViewController:imgPC animated:YES completion:nil];
            }
            
        }break;
        case 2:{
            //NSLog(@"3");
            //从相册选择
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                
                imgPC = [[UIImagePickerController alloc]init];
                imgPC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                // 媒体类型——相册
                imgPC.mediaTypes = @[(NSString*)kUTTypeImage];
                imgPC.allowsEditing = YES;
                imgPC.delegate = self;
                
                [self presentViewController:imgPC animated:YES completion:nil];
            }
        }break;
        default:
            break;
    }
}

#pragma mark - UIImagePickerControllerDelegate

// 拍摄完成后要执行的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    // 处理照片
    if ([mediaType isEqualToString:(NSString*)kUTTypeImage]) {
        UIImage *origImg;//原始图片
        UIImage *editedImg;//编辑后的图片
        // 获取原始图片
        origImg = [info objectForKey:UIImagePickerControllerOriginalImage];
        // 获取编辑后的图片
        editedImg = [info objectForKey:UIImagePickerControllerEditedImage];
        
        if (editedImg) {
            image = editedImg;
        }else{
            image = origImg;
        }
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            // 保存到相机胶卷（相册图库）
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        }
        if ([state isEqualToString:@"company"]) {
            compangImage.image = image;
        }else{
            personImage.image = image;
        }
        NSData *imageData = UIImagePNGRepresentation(image);
        imgFileByte = [imageData hexadecimalString];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

// 点击cancel后执行的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}


// 获取当前时间
- (NSString*)getCurrentDateTime {
    NSDate *senddate=[NSDate date];
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"YYYYMMddhhmmss"];
    
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    
    //NSLog(@"locationString:%@",locationString);
    
    return locationString;
}

#pragma mark http Method

-(void)postInfo{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        //BOOL b = postHud.hidden;
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            if (postUpload) {
                postHud.hidden = NO;
                return;
            }
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在发布，请稍后...";
        }
        
        postUpload = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        postUpload.requestMethod = @"POST";
        // 设置超时时间
        postUpload.timeOutSeconds = 60;
        postUpload.delegate = self;
        // 设置参数
        NSString *actionStr = [NSString string];
        if (add) {
            actionStr = @"IDCacdadd";
        }else{
            actionStr = @"IDCardupdate";
        }
        if ([state isEqualToString:@"company"]) {
            paramsDict = @{@"uid":UNAME,@"uid":UID,@"ccode":path};
        }else{
            paramsDict = @{@"uid":UNAME,@"uid":UID,@"cidcard":path};
        }
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, actionStr,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        postUpload.postBody = [paramsData mutableCopy];
        
        [postUpload startAsynchronous];
    }
}

-(void)postRequest{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        //BOOL b = postHud.hidden;
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            if (postUpload) {
                postHud.hidden = NO;
                return;
            }
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在发布，请稍后...";
        }
        
        postUploadFile = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        postUploadFile.requestMethod = @"POST";
        // 设置超时时间
        postUploadFile.timeOutSeconds = 60;
        postUploadFile.delegate = self;
        // 设置参数
        filename = [self getCurrentDateTime];
        NSString *actionStr = @"";
        actionStr = @"fileupload1";
        filename = [NSString stringWithFormat:@"%@.png",filename];
        paramsDict = @{@"uid":UNAME,@"cid":UID,@"filename":filename,@"filebyte":imgFileByte};//uid会员名;filename文件名;filebyte文件文件（btye字节【须将字节数组转化为16进制】）
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, actionStr,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        postUploadFile.postBody = [paramsData mutableCopy];
        
        [postUploadFile startAsynchronous];
    }
    
}
#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    postHud.hidden = YES;
    if (request == postUploadFile) {
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        
        // 1. 是否解析有错误
        if (!err) {
            
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                
                // 文件（图片、视频）上传成功
                NSDictionary *info = result[@"info"];
                
                    path = info[@"filepath"];//图片地址
                    //imgFilePath = [NSString stringWithFormat:@"%@%@",URL_DOMAIN,info[@"filepath"]];//图片地址
                    //                    if (selectedIndex_ == 2) {
                    //                        isVideo = YES;
                    //                    }
    
                [self postInfo];//发送提交请求
                
            } else {
                [postHud hide:YES];
                postHud = Nil;
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
        } else {
            [postHud hide:YES];
            postHud = Nil;
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
    }else if(request == postUpload){
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        // 1. 是否解析有错误
        if (!err) {
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                [postHud hide:YES];
                postHud = Nil;
                // NSDictionary *info = result[@"info"];
                //NSString *newsId = info[@"id"];
                
                [SVProgressHUD showSuccessWithStatus:@"发布成功！"];
                // 提示发布成功
                double delayInSeconds = 2.0;
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    [self.navigationController popViewControllerAnimated:YES];
                });
            } else {
                [postHud hide:YES];
                postHud = Nil;
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
        } else {
            [postHud hide:YES];
            postHud = Nil;
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
    }else{
        NSError *err;
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
        // 1. 是否解析有错误
        if (!err) {
            // 2. 判断错误码
            NSInteger errorCode = [result[@"errorCode"]integerValue];
            if (errorCode == 0) {
                [postHud hide:YES];
                postHud = Nil;
                NSDictionary *info = result[@"info"];
                path1 = info[@"Ccode"];//企业图
                path2 = info[@"CIDcard"];
                if ([info[@"Ccode"] isEqualToString: @""] || [info[@"CIdcard"] isEqualToString: @""] ) {
                    add = YES;
                }else{
                    add = NO;
                    [compangImage sd_setImageWithURL:info[@"Ccode"] placeholderImage:PLACE_HODER_IMG];
                    [personImage sd_setImageWithURL:info[@"CIdcard"] placeholderImage:PLACE_HODER_IMG];
                    
                }
                
            } else {
                [postHud hide:YES];
                postHud = Nil;
                [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
            }
        } else {
            [postHud hide:YES];
            postHud = Nil;
            [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
        }
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    [postHud hide:YES];
    //BOOL b = postHud.hidden;
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

-(void)dealloc{
    [postUploadFile cancel];
    [postUpload cancel];
    [getCardMain cancel];
    postUpload = nil;
}
@end
